import axios from 'axios'
import { loacl } from '@/utils/local'
import { Message } from 'element-ui'
// 引入进度条
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'

// ajax封装请求工具函数、
// 请求根路径
axios.defaults.baseURL = 'http://127.0.0.1:5000'
    // 请求超时时间
axios.defaults.timeout = 10000

// 请求拦截器
axios.interceptors.request.use(
    config => {
        nprogress.start()
        let token = loacl.get('token_userlogin')
        if (token) {
            config.headers.authorization = token
        }
        return config
    },
    err => {
        return Promise.reject(err)
    }
)

// 响应拦截器
axios.interceptors.response.use(
    response => {
        nprogress.done()
        let { code, msg } = response.data
        if (code === 0) {
            Message({
                message: msg,
                type: 'success'
            })
        }
        if (code === 1) {
            Message.error(msg)
        }
        return response
    },
    err => {
        if (err.response.data.code === 401) {
            loacl.clear()
            window.location.href = 'http://localhost:8080/#/login'
        }
        return Promise.reject(err)
    }
)

export default axios